package com.yonyou.iuap.controller.pc;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.yonyou.iuap.base.intf.IUserAdminService;
import com.yonyou.iuap.base.utils.BaseToolsUtils;
import com.yonyou.iuap.controller.pc.PCShellUserController.Role;
import com.yonyou.iuap.pub.JsonUtils;
import com.yonyou.iuap.shell.entity.BdIndustryChartEntity;
import com.yonyou.iuap.shell.entity.exp.BdKnowledgeCategoryEntityVo;
import com.yonyou.iuap.shell.entity.exp.UserRolePoJo;
import com.yonyou.iuap.shell.pub.RequestDto;
import com.yonyou.iuap.shell.pub.ResultDto;
import com.yonyou.iuap.shell.service.impl.KmCategoryServiceImpl;
import com.yonyou.iuap.shell.service.intf.IIndustryChartService;
import com.yonyou.iuap.shell.service.intf.IKmPublishService;
import com.yonyou.iuap.utils.PropertyUtil;

/**
 * 关键字 表
 * 
 * @author shiwenqiang
 * @author liuguicen
 * **/
@Controller
@RequestMapping("/PCIndustryChart")
@SessionAttributes("icon_name")
public class PCIndustryChartController {
	private final Logger logger = (Logger) LoggerFactory.getLogger(getClass());
	private long start,end;
	@Autowired
	private IIndustryChartService industryChartService;
	@Autowired
	private IUserAdminService userService;
	@Autowired
	private IKmPublishService kmPublishService;
	@RequestMapping(value = "pc/ztreeQuery", method = RequestMethod.POST)
	public @ResponseBody String LikeIKnowledgeCategory(@RequestBody Map map,HttpServletRequest request,HttpServletResponse response) {
		start=System.currentTimeMillis();
		ResultDto rsdto = new ResultDto();
		String param=" 1=1 ";
		if(map.get("level")!=null&&(Integer)map.get("level")==1){
//			不显示一级
			param="cate_type not IN (101)";
		}else if(map.get("level")!=null&&(Integer)map.get("level")==2){
//			不显示一级、二级
			param="cate_type not IN (101,102)";
		}
		rsdto = industryChartService.queryTree(param,0,"0");
		request.getSession().getAttribute("icon_name");
		String rs_json = JsonUtils.toJsonStr(rsdto);
		end=System.currentTimeMillis();
		logger.info("ztreeQuery接口调用时间"+String.valueOf(end-start));
		return rs_json;
	}
	@RequestMapping(value = "/queryBycondition", method = RequestMethod.POST)
	public @ResponseBody String queryBycondition(@RequestBody Map map,HttpServletRequest request,HttpServletResponse response) {
		start=System.currentTimeMillis();
		ResultDto rsdto = new ResultDto();
		String paramString="";
//		2查询所有二级行业关键字，3查询所有三级行业关键字
		if((Integer)map.get("level")==2){
			paramString=" CATE_TYPE=102 ORDER BY  order_num,nlssort( cate_name,'NLS_SORT=SCHINESE_PINYIN_M')";
		}else if((Integer)map.get("level")==3){
			paramString=" CATE_TYPE=0 ORDER BY  order_num,nlssort( cate_name,'NLS_SORT=SCHINESE_PINYIN_M')";
		}
		rsdto = industryChartService.selectByCondition(paramString);
		String rs_json = JsonUtils.toJsonStr(rsdto);
		end=System.currentTimeMillis();
		logger.info("queryBycondition接口调用时间"+String.valueOf(end-start));
		return rs_json;
	}

	/**
	 * 添加行业部件信息
	 * 
	 * @param parMap
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/insert", method = RequestMethod.POST)
	public @ResponseBody String insert(@RequestBody HashMap parMap,
			HttpServletRequest request, HttpSession session) {
		start=System.currentTimeMillis();
		/*系统管理员权限校验 begin*/
		ResultDto userDto = userService.checkUserIsSysManager(parMap.get("userid")==null?"":parMap.get("userid").toString());
		if(userDto.getStatus()!=0){
			return JsonUtils.toJsonStr(userDto);
		}
		/*系统管理员权限校验 end*/
		ResultDto resultDto = new ResultDto();
		try {
			BdIndustryChartEntity entity = new BdIndustryChartEntity();
			// 父节点
			String fw_parent = parMap.get("fw_parent").toString();
			entity.setFw_parent(fw_parent);
			// 树编码
			if (fw_parent != null && !StringUtils.isEmpty(fw_parent)) {// 存在父节点
				BdIndustryChartEntity parentEntity = (BdIndustryChartEntity) industryChartService
						.selectByPrimaryKey(fw_parent).getData();
				entity.setFw_tc(parentEntity.getCate_code());
				//这个字段废弃，有cate_type就行，同时一级二级行业只能我们手动修改数据库增加，六级：101，102，0,1,2,3
//				entity.setFw_level(parentEntity.getFw_level() + 1);
				if(parentEntity.getCate_type()==102){
					entity.setCate_type(0);
				}else{
					entity.setCate_type(parentEntity.getCate_type() + 1);
				}
			} else {
//				entity.setFw_level(0);
				entity.setCate_type(101);
				entity.setIcon_url("http://"+BaseToolsUtils.getPropertiesValue("encrypt_ftp_ip")
						+BaseToolsUtils.getPropertiesValue("encrypt_htttp_hz")
						+"images/"+session.getAttribute("icon_name"));
			}

			// 名字
			String cate_name = parMap.get("cate_name").toString();
			entity.setCate_name(cate_name);
			//判断重复
//			String paramString="cate_name = '"+cate_name+"'";
//			resultDto=industryChartService.countByCondition(paramString);
			if(isNameRepeat(fw_parent,cate_name)){
				resultDto.setMessage("关键字重复");
				resultDto.setStatus(1);
				return JsonUtils.toJsonStr(resultDto);
			}

			// 序列号
			BigDecimal order_num = new BigDecimal(
					(parMap.get("order_num").toString()));
			entity.setOrder_num(order_num);
			//是否启用
			if(parMap.get("enable")!=null){
				String enable=parMap.get("enable").toString();
				entity.setSeal_mark(enable);
			}else{
				entity.setSeal_mark("Y");
			}

			resultDto = industryChartService.insert(entity);
		} catch (NullPointerException e) {
			resultDto.setMessage("空指针,参数错误或缺少参数");
			resultDto.setStatus(1);
		} 
		end=System.currentTimeMillis();
		logger.info("insert接口调用时间"+String.valueOf(end-start));
		return JsonUtils.toJsonStr(resultDto);
	}

	/*
	 * 删除，有子节点是不允许删除
	 */
	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	public @ResponseBody String delete(@RequestBody HashMap parMap,
			HttpServletRequest request, HttpServletResponse response) {
		start=System.currentTimeMillis();
		/*系统管理员权限校验 begin*/
		ResultDto userDto = userService.checkUserIsSysManager(parMap.get("userid")==null?"":parMap.get("userid").toString());
		if(userDto.getStatus()!=0){
			return JsonUtils.toJsonStr(userDto);
		}
		/*系统管理员权限校验 end*/
		ResultDto resultDto = new ResultDto();
		try {
			// 检查是否含有子节点，若有，不允许删除
			String pk_industry_chart = parMap.get("pk_industry_chart")
					.toString();
			List<BdIndustryChartEntity> exitList = (List<BdIndustryChartEntity>) innerSelectByCondition(
					pk_industry_chart).getData();
			if (exitList.size() > 0) {
				resultDto.setStatus(1);
				resultDto.setMessage("不能删除含有子节点的数据 ");
			} else {
				resultDto = industryChartService
						.deleteByPrimaryKey(pk_industry_chart);
			}
		} catch (NullPointerException e) {
			resultDto.setMessage("空指针,参数错误或缺少参数");
			resultDto.setStatus(1);
		}
		end=System.currentTimeMillis();
		logger.info("delete接口调用时间"+String.valueOf(end-start));
		return JsonUtils.toJsonStr(resultDto);
	}

	/*
	 * 更新，目前只能修改名称和显示序号
	 */
	@RequestMapping(value = "/update", method = RequestMethod.POST)
	public @ResponseBody String update(@RequestBody HashMap parMap,
			HttpServletRequest request, HttpServletResponse response) {
		start=System.currentTimeMillis();
		//系统管理员权限校验 begin
		ResultDto userDto = userService.checkUserIsSysManager(parMap.get("userid")==null?"":parMap.get("userid").toString());
		if(userDto.getStatus()!=0){
			return JsonUtils.toJsonStr(userDto);
		}
		/*系统管理员权限校验 end*/
		ResultDto resultDto = new ResultDto();
		try {

			String pk_industry_chart = parMap.get("pk_industry_chart")
					.toString();
			BdIndustryChartEntity entity = (BdIndustryChartEntity) industryChartService
					.selectByPrimaryKey(pk_industry_chart).getData();
			String oldkey=entity.getCate_name();
			// 名字
			String cate_name = parMap.get("cate_name").toString();
			entity.setCate_name(cate_name);

			// 序列号
			BigDecimal order_num = new BigDecimal(
					(parMap.get("order_num").toString()));
			entity.setOrder_num(order_num);
			
			//是否启用
			if(parMap.get("enable")!=null){
				String enable=parMap.get("enable").toString();
				entity.setSeal_mark(enable);
			}
//			更新已发布知识关键字
			Map<String,String> map=new HashMap<String, String>();
			map.put("oldkey", oldkey);
			map.put("newkey", cate_name);
			kmPublishService.updateKey(map);
			resultDto = industryChartService.updateByPrimaryKeySelective(entity);
		} catch (NullPointerException e) {
			resultDto.setMessage("空指针,参数错误或缺少参数");
			resultDto.setStatus(1);
		}
		end=System.currentTimeMillis();
		logger.info("update接口调用时间"+String.valueOf(end-start));
		return JsonUtils.toJsonStr(resultDto);
	}

	/*
	 * 查询某个节点下面的所有的数据 fw_parent=0表示顶级
	 */
	@RequestMapping(value = "/quaryAllChild", method = RequestMethod.POST)
	public @ResponseBody String quaryAllChild(@RequestBody HashMap parMap,
			HttpServletRequest request, HttpServletResponse response) {
		start=System.currentTimeMillis();
		ResultDto resultDto = new ResultDto();
		try {
			// 父节点
			String fw_parent = parMap.get("fw_parent").toString();
			resultDto = innerSelectByCondition(fw_parent);
		} catch (NullPointerException e) {
			resultDto.setMessage("空指针,参数错误或缺少参数");
			resultDto.setStatus(1);
		} 
		end=System.currentTimeMillis();
		logger.info("quaryAllChild接口调用时间"+String.valueOf(end-start));
		return JsonUtils.toJsonStr(resultDto);
	}

	/*
	 * 查询某个节点
	 */
	@RequestMapping(value = "/quaryNode", method = RequestMethod.POST)
	public @ResponseBody String quaryNode(@RequestBody HashMap parMap,
			HttpServletRequest request, HttpServletResponse response) {
		start=System.currentTimeMillis();
		ResultDto resultDto = new ResultDto();
		try {
			String pk_industry_chart = parMap.get("pk_industry_chart")
					.toString();
			BdIndustryChartEntity entity = (BdIndustryChartEntity) industryChartService
					.selectByPrimaryKey(pk_industry_chart).getData();
			resultDto.setData(entity);
		} catch (NullPointerException e) {
			resultDto.setMessage("空指针,参数错误或缺少参数");
			resultDto.setStatus(1);
		} 
		end=System.currentTimeMillis();
		logger.info("quaryNode接口调用时间"+String.valueOf(end-start));
		return JsonUtils.toJsonStr(resultDto);
	}

	private ResultDto innerSelectByCondition(String fw_parent) {
		String condidion = "fw_parent='" + fw_parent + "'";
		ResultDto resultDto = industryChartService.selectByCondition(condidion);
		// 是否添加序列号
		return resultDto;
	}

	/**
	 * 检测名称重复，暂未使用
	 * 
	 * @param parent_pk
	 * @param cate_name
	 * @return
	 */
	private boolean isNameRepeat(String parent_pk, String cate_name) {
		String condidion = "fw_parent='" + parent_pk + "'";
		ResultDto resultDto = industryChartService.selectByCondition(condidion);
		List<BdIndustryChartEntity> list = (List<BdIndustryChartEntity>) resultDto
				.getData();
		for (BdIndustryChartEntity vo : list) {
			if (vo.getCate_name().equals(cate_name)) {
				return true;
			}
		}
		return false;
	}
	
}
